package com.health.trans.service.action;

import cn.hutool.core.collection.CollUtil;
import com.health.es.entity.log.TransformLog;
import com.health.es.temp.EsHelper;
import com.health.trans.channel.MemorySet;
import com.health.trans.service.AsyncDataService;
import com.health.trans.service.CorrelationService;
import lombok.Data;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;

/**
 * @author nqlz
 */
@Data
public class TransAction<T, J> {

    protected final CorrelationService correlationService;

    protected Class<T> tClass;

    protected MemorySet memorySet;

    protected TransAction(Class<T> tClass, CorrelationService correlationService) {
        this.tClass = tClass;
        this.correlationService = correlationService;
        this.memorySet = AsyncDataService.getChannel(tClass);
    }

    protected TransAction(CorrelationService correlationService) {
        this.correlationService = correlationService;
        this.tClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        this.memorySet = AsyncDataService.getChannel(tClass);
    }

    public static <T, J> TransAction<T, J> instance(Class<T> tClass, CorrelationService correlationService) {
        TransAction<T, J> transAction = new TransAction<>(tClass, correlationService);
        transAction.memorySet = AsyncDataService.getChannel(tClass);
        return transAction;
    }

    public void transData(T t) {
        TransformLog transformLog = correlationService.correlation(t);
        if (null == transformLog) {
            //关联性校验通过
            memorySet.pushOther(tClass, t);
        } else {
            //未关联到数据
            checkLog();
            memorySet.pushLog(transformLog);
        }
    }


    public void checkLog() {
        Collection<TransformLog> transformLogs = memorySet.checkLogQueue();
        //elasticsearch 保存 transformLog
        if (CollUtil.isNotEmpty(transformLogs)) {
            EsHelper.operations.save(transformLogs);
        }
    }


}
